// code 5 mutex + RAII
#include "mutex_RAII.hpp"
// critical resource
tickets g_tickets(10000);
void *thread_todo_func(void *argc)
{
    auto *argcs = reinterpret_cast<thread_acgcs *>(argc);
    while (1)
    {
        int ticket_num;
        // critical section
        {
            // RAII
            smart_mutex tickets_mutex(argcs->_pmutex);
            ticket_num = g_tickets.get_ticket();
        }
        if (ticket_num)
        {
            cout << argcs->_name << " get ticket: NO." << ticket_num << endl;
            // other work
            usleep(999);
        }
        else
        {
            cout << argcs->_name << " no ticket left" << endl;
            usleep(123);
            break;
        }
    }
}
int main()
{
    pthread_mutex_t m_mutex;
    pthread_mutex_init(&m_mutex, nullptr);
    pthread_t tid[4]{0, 0, 0, 0};
    thread_acgcs *t_acgcs = new thread_acgcs[4]{
        {"thread_1", &m_mutex},
        {"thread_2", &m_mutex},
        {"thread_3", &m_mutex},
        {"thread_4", &m_mutex}};
    for (int i = 0; i < 4; i++)
        pthread_create(tid + i, nullptr, thread_todo_func, reinterpret_cast<void *>(t_acgcs + i));
    for (int i = 0; i < 4; i++)
        pthread_join(tid[i], nullptr);
    pthread_mutex_destroy(&m_mutex);
    return 0;
}